﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Web;
using System.Xml;
using System.Threading;
using System.Web.SessionState;

/// <summary>
///WebIM_Handler 的摘要说明
/// </summary>
public class WebIM_ReceiveHandler : IHttpAsyncHandler
{
	public WebIM_ReceiveHandler()
	{
	}

	HttpContext m_Context = null;

	IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
	{
		m_Context = context;

		System.IO.Stream inputStream = context.Request.InputStream;
		Byte[] buffer = new Byte[inputStream.Length];
		inputStream.Read(buffer, 0, (int)inputStream.Length);
		string content = context.Request.ContentEncoding.GetString(buffer);
		Hashtable data = Utility.ParseJson(content) as Hashtable;

		WebIM_AsyncResult asyncResult = new WebIM_AsyncResult(cb, extraData);
		Nullable<DateTime> from = data.ContainsKey("From") ? new Nullable<DateTime>((DateTime)data["From"]) : null;

		if (!MessageManagement.Instance.AddListener(data["Receiver"] as string, data["Sender"] as string, from, asyncResult))
		{
			//已有消息，发送消息并结束链接
			asyncResult.Complete(null);
		}

		return asyncResult;
	}

	void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
	{
		//将消息发送到客户端
		WebIM_AsyncResult asyncResult = result as WebIM_AsyncResult;
		asyncResult.Send(m_Context);
	}

	void IHttpHandler.ProcessRequest(HttpContext context)
	{
	}

	bool IHttpHandler.IsReusable
	{
		get { return true; }
	}
}

public class WebIM_AsyncResult : IAsyncResult
{
	AsyncCallback m_AsyncCallback = null;
	object m_Data = null;
	bool m_IsCompleted = false;

	public WebIM_AsyncResult(AsyncCallback callback, Object extraData)
	{
		m_Data = extraData;
		m_AsyncCallback = callback;
	}

	bool IAsyncResult.IsCompleted { get { return m_IsCompleted; } }

	bool IAsyncResult.CompletedSynchronously { get { return false; } }

	WaitHandle IAsyncResult.AsyncWaitHandle { get { return null; } }

	Object IAsyncResult.AsyncState { get { return m_Data; } }

	StringBuilder m_Cache = new StringBuilder();

	public void Write(object content)
	{
		m_Cache.Append(content.ToString());
	}

	public void Send(HttpContext context)
	{
		context.Response.Write(m_Cache.ToString());
	}

	public void Complete(object data)
	{
		m_AsyncCallback(this);
		m_IsCompleted = true;
	}
}
